import axios from "axios";
import { toast } from "~/composables/util";
import { getToken } from "~/composables/auth";
import store from "./store";

const service = axios.create({
  baseURL: "/api",
});

service.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    const token = getToken();
    // const token = cookie.get("admin-token");
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// Add a response interceptor
service.interceptors.response.use(
  function (response) {
    // Do something with response data
    return response.data.data;
  },
  function (error) {
    const msg = error.response.data.msg || "请求失败";
    if (msg == "非法token，请先登录！") {
      store.dispatch("logout").finally(() => location.reload());
    }
    toast(msg, "error");
    return Promise.reject(error);
  }
);
export default service;
